﻿<%@ WebHandler Language="C#" Class="houseCensor" %>

using System;
using System.Web;
using Chenxin.Lib.Utility;
using System.Data;

public class houseCensor : AjaxHandlerBase
{
    public houseCensor()
    {
        htTypePermit.Add("del", Constants.Permit_DelHouse_Base);
        htTypePermit.Add("export", Constants.Permit_ExportHouseCensor);
    }

    override public void RequestProcess(HttpContext context)
    {
        context.Response.AddHeader("pragma", "no-cache");
        context.Response.AddHeader("cache-control", "");
        context.Response.CacheControl = "no-cache";

        if (context.Request["op"] != null)
        {
            switch (context.Request["op"].ToLower())
            {
                case "gethouselist":
                    GetHouseList(context);
                    break;
                case "gethousetracelist":
                    GetHouseTraceList(context);
                    break;
                case "gethouseinfo":
                    GetHouseInfo(context);
                    break;
                case "getlist":
                    //GetList(context);
                    break;
                case "getmodel":
                    //GetModel(context);
                    break;
                case "loadcommunity":
                    LoadCommunity(context);
                    break;
                case "edit":
                    Edit(context);
                    break;
                case "del":
                    Del(context);
                    break;
                case "a":
                    break;
                case "b":
                    break;
                case "export":
                    context.Response.Write("{success:'1',msg:'',data:''}");
                    break;
                default:
                    break;
            }
        }
    }

    /// <summary>
    /// 删除一条记录
    /// </summary>
    /// <param name="context"></param>
    private void Del(HttpContext context)
    {
        try
        {
            if (context.Request["modelid"] != null)
            {
                Chenxin.Lib.House.Entity.House_BaseInfo model = Chenxin.Lib.House.DAL.House_BaseInfo.GetModel(new Guid(context.Request["modelid"]));
                if (model == null)
                {
                    context.Response.Write("{success:'0',msg:'获取数据记录出错，记录不存在！！',data:''}");
                    return;
                }
                
                model.Status = -10;
                model.UpdateTime = DateTime.Now;
                Chenxin.Lib.House.DAL.House_BaseInfo.Update(model);
                //清除缓存
                string strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_HOUSEINFO, model.HouseId);
                Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
                cs.Delete(strCachKey);
                context.Response.Write("{success:'1',msg:'删除成功！',data:''}");
            }
            else
            {
                context.Response.Write("{success:'0',msg:'删除失败,请选择一条记录！',data:''}");
            }
        }
        catch
        {
            context.Response.Write("{success:'0',msg:'删除失败！',data:''}");
        }
    }

    //*******************************************
    //功能概要       ：响应字符串
    //参数説明       ：model
    //返回值説明     ：bool
    //功能詳細       ：权限检查
    //作成者         ： 
    //作成日         ：
    //修改者         ：
    //修改日         ：
    //状态           ：修改前
    //*******************************************
    //private bool CheckDelPemit(Chenxin.Lib.House.Entity.House_BaseInfo model)
    //{
    //    if (CurrentUserInfo.UserType == 100)
    //    {
    //        return true;
    //    }
    //    if (CurrentUserInfo.ContainsPermit(Constants.Permit_DelAllHouse))
    //    {
    //        return true;
    //    }
    //    if (CurrentUserInfo.ContainsPermit(Constants.Permit_DelCityHouse))
    //    {
    //        if (model.CityId == CurrentUserInfo.CityId)
    //        {
    //            return true;
    //        }
    //    }

    //    if (CurrentUserInfo.ContainsPermit(Constants.Permit_DelCompanyHouse))
    //    {
    //        if (model.CompanyId == CurrentUserInfo.CompanyId)
    //        {
    //            return true;
    //        }
    //    }
    //    if (CurrentUserInfo.ContainsPermit(Constants.Permit_DelDepartHouse))
    //    {
    //        if (Chenxin.Lib.Hr.DAL.Struct_UserDepartRelation.Exists(string.Format(" and UserId='{0}' and DepartId='{1}'", CurrentUserInfo.UserId, CurrentUserInfo.DepartId)))
    //        {
    //            return true;
    //        }
    //    }
    //    return false;
    //}

    //*******************************************
    //功能概要       ：响应字符串
    //参数説明       ：context
    //返回值説明     ：bool,strMsg
    //功能詳細       ：权限检查
    //作成者         ： 
    //作成日         ：
    //修改者         ：zou.xiaochun
    //修改日         ：2010-06-13
    //状态           ：修改后
    //*******************************************
    public override bool CustomerCheckPermint(HttpContext context, out string strMsg)
    {
        if (context.Request["op"] != null)
        {
            //临时变量
            string op = context.Request["op"];
            string id = context.Request["modelid"];

            //实体变量
            Chenxin.Lib.House.Entity.House_BaseInfo model = null;
            
            //传递参数用
            System.Collections.Hashtable per = new System.Collections.Hashtable();
            System.Collections.Hashtable confine = new System.Collections.Hashtable();

            //删除
            if ("del".Equals(op))
            {
                model = Chenxin.Lib.House.DAL.House_BaseInfo.GetModel(new Guid(id));
                if (model == null)
                {
                    strMsg = "{success:0,msg:'房源删除失败！',data:''}";
                    return false;
                }

                //加如权限项
                per.Add("ALL", Constants.Permit_DelAllHouse);
                per.Add("CITY", Constants.Permit_DelCityHouse);
                per.Add("COMPANY", Constants.Permit_DelCompanyHouse);
                per.Add("DEPART", Constants.Permit_DelDepartHouse);

                //加入范围
                confine.Add("CityId", model.CityId);
                confine.Add("CompanyId", model.CompanyId);
                confine.Add("OperatorId", model.OprPersonId);
                
                //检查权限
                return CheckPermint(per, confine, checkDepartPermit(model, op), out strMsg);
            }
        }
        strMsg = "{success:1,msg:'',data:{permit:true}}";
        return true;
    }

    //*******************************************
    //功能概要       ：部门内有无封盘解盘权限
    //参数説明       ：context 上下文
    //返回值説明     ：bool
    //功能詳細       ：部门内有无封盘解盘权限
    //作成者         ：zou.xiaochun 
    //作成日         ：2010-06-13
    //修改者         ：
    //修改日         ：
    //*******************************************
    public bool checkDepartPermit(Chenxin.Lib.House.Entity.House_BaseInfo model, string op)
    {
        if (model.OprPersonId.Equals(CurrentUserInfo.UserId))
            return true;
        //检查有无权限
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        sb.AppendFormat(" (Departid = '{0}' AND UserId = '{1}' and DelHouse=1)", model.OprDepartId, CurrentUserInfo.UserId);
        System.Collections.Generic.List<Chenxin.Lib.Hr.Entity.Struct_UserDepartRelation> list = Chenxin.Lib.Hr.DAL.Struct_UserDepartRelation.GetListArray(sb.ToString());
        if (list.Count > 0)
        {
            return true;
        }
        return false;
    }

    /// <summary>
    /// 根据拼音字母或者文字，查询符合条件的楼盘
    /// </summary>
    /// <param name="context"></param>
    private void LoadCommunity(HttpContext context)
    {
        Guid departId = CurrentUserInfo.DepartId;
        string strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_DEPART_SETTINGS, departId);
        Chenxin.Lib.House.Entity.House_BusinessSetting setting = null;

        Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
        setting = cs.GetObject<Chenxin.Lib.House.Entity.House_BusinessSetting>(strCachKey);
        if (!cs.Hit)
        {
            setting = Chenxin.Lib.House.DAL.House_BusinessSetting.GetModel(departId);
            if (setting != null) cs.Set(strCachKey, setting);
        }

        string strCitys = "";

        if (setting != null)
        {
            if (!string.IsNullOrEmpty(setting.CanAddAtCityId)) strCitys = setting.CanAddAtCityId;
        }

        if (strCitys == "") strCitys = CurrentUserInfo.CityId.ToString();

        System.Text.StringBuilder sbwhere = new System.Text.StringBuilder();

        string[] aryCity = strCitys.Split(new char[] { ',' });
        foreach (string strCityId in aryCity)
        {
            if (string.IsNullOrEmpty(strCityId)) continue;
            if (sbwhere.Length == 0)
                sbwhere.AppendFormat("((CityId = '{0}')", strCityId);
            else
                sbwhere.AppendFormat(" OR (CityId = '{0}')", strCityId);
        }
        if (sbwhere.Length > 0) sbwhere.Append(")");

        if (sbwhere.Length > 0)
            sbwhere.Append(" AND (Status=1) ");
        else
            sbwhere.Append(" (Status=1) ");

        if (context.Request["query"] != null)
        {
            sbwhere.AppendFormat(" AND (CommunityName like '%{0}%' OR Py like '%{0}%') ", context.Request["query"]);

            DataTable dt = Chenxin.Lib.House.DAL.Community_BaseInfo.GetList(sbwhere.ToString(), "CommunityName desc", 30).Tables[0];

            System.Text.StringBuilder sugestionSb = new System.Text.StringBuilder();

            foreach (DataRow dr in dt.Rows)
            {
                sugestionSb.AppendFormat("'{0}',", dr["CommunityName"]);
            }
            context.Response.Write(string.Format("{{query:'{0}',suggestions:[{1}],{2}}}", context.Request["query"], sugestionSb.Length > 0 ? sugestionSb.Remove(sugestionSb.Length - 1, 1).ToString() : sugestionSb.ToString(), JsonHelp.Convert2Json(dt).Replace("\"rows\"", "data")));
        }
    }


    /// <summary>
    /// 返回房源列表；
    /// 根据查询参数生成查询条件1,根据权限设定生成查询条件2；
    /// 返回Json数据：{count:'30',data:'abc'}
    /// </summary>
    /// <param name="context"></param>
    private void GetHouseList(HttpContext context)
    {
        string responseJson = "";
        try
        {
            int iPageIndex = (string.IsNullOrEmpty(context.Request["pageindex"])) ? 1 : int.Parse(context.Request["pageindex"]) + 1;//页码
            int iPageSize = (string.IsNullOrEmpty(context.Request["pagesize"])) ? 30 : int.Parse(context.Request["pagesize"]);//页记录数
            string strCommunity = context.Request["community"];//楼盘
            string strCommunityId = context.Request["communityid"];//楼盘
            string strRegion = context.Request["region"];//区域；
            string strBlock = context.Request["block"];//板块
            int iStatus = string.IsNullOrEmpty(context.Request["status"]) ? 1000 : int.Parse(context.Request["status"]);//房源状态
            int iBussines = string.IsNullOrEmpty(context.Request["business"]) ? 1000 : int.Parse(context.Request["business"]);//交易类型
            string strHouseUse = context.Request["houseuse"];//房屋用途
            string strBuildingType = context.Request["buildingtype"];//建筑类型
            string strLowPrice = context.Request["lowprice"];//最低价
            string strHightPrice = context.Request["heightprice"];//最高价
            string strKeyword = context.Request["keyword"];//智能
            string strUserCode = context.Request["usercode"];//工号
            string strDayType = context.Request["daytype"];//日期类型
            string strDayBegin = context.Request["daybegin"];//开始日期
            string strDayEnd = context.Request["dayend"];//结束日期
            string strOrderField = context.Request["order"];//排序字段名
            string timetrace = context.Request["timetrace"];

            Guid cityId = (string.IsNullOrEmpty(context.Request["cityid"])) ? Guid.Empty : new Guid(context.Request["cityid"]);
            Guid companyId = (string.IsNullOrEmpty(context.Request["companyid"])) ? Guid.Empty : new Guid(context.Request["companyid"]);
            Guid areaId = (string.IsNullOrEmpty(context.Request["areaid"])) ? Guid.Empty : new Guid(context.Request["areaid"]);
            Guid departId = (string.IsNullOrEmpty(context.Request["departid"])) ? Guid.Empty : new Guid(context.Request["departid"]);
            Guid userId = (string.IsNullOrEmpty(context.Request["userid"])) ? Guid.Empty : new Guid(context.Request["userid"]);


            string fieldlist = " IsMarked,Kind, IsTrust, IsHavekey, IsHot, IsProtectPhone, Status, Region, Community, " +
                "CommunityId, BuildingId, BuildingName, Room, BusinessKind, BuildingArea, SalePrice_T, RentPrice," +
                "OprDepartId, OprDepart, OprPersonId, OprPerson, ServiceTime,HouseId,CustomerName,CustTel1 ";

            string tablefieldlist = " IsMarked,BusinessKind as Kind, IsTrust, IsHavekey, IsHot, IsProtectPhone, " +
                "case Status when 10 then '有效' when -1 then '无效' when 20 then '暂缓' when 30 then '封盘' when -10 then '删除' end as Status," +
                "Region, Community,case BusinessKind when '20' then '出租' when '10' then '出售' else '租售' end as BusinessKind, " +
                "CommunityId, BuildingId, BuildingName, Room, BuildingArea, floor(SalePrice_T/10000) as SalePrice_T, floor(RentPrice) as RentPrice ," +
                "OprDepartId, OprDepart, OprPersonId, OprPerson, ServiceTime,HouseId,CustomerName," +
                "(select isnull(Mobile,'')+'/'+isnull(Phone,'') from Customer_BaseInfo where Customer_BaseInfo.CustomerId=House_BaseInfo.CustomerId) as CustTel1";

            System.Text.StringBuilder sb1 = new System.Text.StringBuilder();

            //判断楼盘
            if (!string.IsNullOrEmpty(strCommunityId))
            {
                sb1.AppendFormat(" AND (CommunityId ='{0}')", strCommunityId);
            }
            else
            {
                if (!string.IsNullOrEmpty(strCommunity)) sb1.AppendFormat(" AND (Community Like '%{0}%')", strCommunity);
            }

            if (!string.IsNullOrEmpty(strRegion)) sb1.AppendFormat(" AND (Region = '{0}')", strRegion);
            if (!string.IsNullOrEmpty(strBlock)) sb1.AppendFormat(" AND (Block = '{0}')", strBlock);
            if (!string.IsNullOrEmpty(strBlock)) sb1.AppendFormat(" AND (Block = '{0}')", strBlock);
            if (iStatus != 1000)
                sb1.AppendFormat(" AND (Status = {0})", iStatus);
            else
                sb1.Append(" AND (Status > -10)");

            if (iBussines != 1000) sb1.AppendFormat(" AND (BusinessKind = {0})", iBussines);
            if (!string.IsNullOrEmpty(strHouseUse)) sb1.AppendFormat(" AND (HouseUse = '{0}')", strHouseUse);
            if (!string.IsNullOrEmpty(strBuildingType)) sb1.AppendFormat(" AND (BuildingType = '{0}')", strBuildingType);

            if ("10".Equals(timetrace))
            {
                sb1.Append(" and ((DATEADD(hh,48,(House_BaseInfo.Adddate ))) < (select min(House_TraceInfo.TraceTime) from House_TraceInfo where House_TraceInfo.TractorId=House_BaseInfo.OprPersonId and House_TraceInfo.HouseId=House_BaseInfo.HouseId and House_TraceInfo.status =0)  ");
                sb1.Append(" OR ((select min(House_TraceInfo.TraceTime) from House_TraceInfo where House_TraceInfo.TractorId=House_BaseInfo.OprPersonId and House_TraceInfo.HouseId=House_BaseInfo.HouseId and status =0) is null and ((DATEADD(hh,48,(House_BaseInfo.Adddate)) < getdate())))) ");
            }
            #region 价格判断
          /*  if (!string.IsNullOrEmpty(strLowPrice))
            {
                if (iBussines != 1000)
                {
                    switch (iBussines)
                    {
                        case 10:
                            sb1.AppendFormat(" AND (SalePrice_T >={0})", strLowPrice);
                            break;
                        case 20:
                            sb1.AppendFormat(" AND (SalePrice_T >={0})", strLowPrice);
                            break;
                        case 30:
                            sb1.AppendFormat(" AND ((SalePrice_T >={0}) OR (RentPrice>={0}))", strLowPrice);
                            break;
                    }
                }
                else
                {
                    sb1.AppendFormat(" AND ((SalePrice_T >={0}) OR (RentPrice>={0}))", strLowPrice);
                }
            }

            if (!string.IsNullOrEmpty(strHightPrice))
            {
                if (iBussines != 1000)
                {
                    switch (iBussines)
                    {
                        case 10:
                            sb1.AppendFormat(" AND (SalePrice_T <={0})", strHightPrice);
                            break;
                        case 20:
                            sb1.AppendFormat(" AND (SalePrice_T <={0})", strHightPrice);
                            break;
                        case 30:
                            sb1.AppendFormat(" AND ((SalePrice_T <={0}) OR (RentPrice<={0}))", strHightPrice);
                            break;
                    }
                }
                else
                {
                    sb1.AppendFormat(" AND ((SalePrice_T <={0}) OR (RentPrice<={0}))", strHightPrice);
                }
            }*/
            if (!string.IsNullOrEmpty(strLowPrice) && !string.IsNullOrEmpty(strHightPrice))
            {
                decimal lprice = Convert.ToDecimal(strLowPrice) * 10000;
                decimal hprice = Convert.ToDecimal(strHightPrice) * 10000;
                if (iBussines != 1000)
                {
                    switch (iBussines)
                    {
                        case 10:
                            sb1.AppendFormat(" AND (SalePrice_T >={0}) AND (SalePrice_T <={1})", lprice, hprice);
                            break;
                        case 20:
                            sb1.AppendFormat(" AND (RentPrice >={0}) AND(RentPrice <={1})", lprice, hprice);
                            break;
                        case 30:
                            sb1.AppendFormat(" AND (((SalePrice_T <={0}) and (SalePrice_T >={1})) or ((RentPrice<={0})  and (RentPrice>={1})))", hprice, lprice);
                            break;
                    }
                }
                else
                {
                    sb1.AppendFormat(" AND (((SalePrice_T <={0}) and (SalePrice_T >={1})) or ((RentPrice<={0})  and (RentPrice>={1})))", hprice, lprice);
                }
            }
            else if (!string.IsNullOrEmpty(strLowPrice) && string.IsNullOrEmpty(strHightPrice))
            {
                decimal lprice = Convert.ToDecimal(strLowPrice) * 10000;
                if (iBussines != 1000)
                {
                    switch (iBussines)
                    {
                        case 10:
                            sb1.AppendFormat(" AND (SalePrice_T >={0})", lprice);
                            break;
                        case 20:
                            sb1.AppendFormat(" AND (RentPrice >={0})", lprice);
                            break;
                        case 30:
                            sb1.AppendFormat(" AND ((SalePrice_T >={0}) OR (RentPrice>={0}))", lprice);
                            break;
                    }
                }
                else
                {
                    sb1.AppendFormat(" AND ((SalePrice_T >={0}) and (RentPrice>={0}))", strLowPrice);
                }

            }
            else if (!string.IsNullOrEmpty(strHightPrice) && string.IsNullOrEmpty(strLowPrice))
            {
                decimal hprice = Convert.ToDecimal(strHightPrice) * 10000;
                if (iBussines != 1000)
                {
                    switch (iBussines)
                    {
                        case 10:
                            sb1.AppendFormat(" AND (SalePrice_T <={0})", hprice);
                            break;
                        case 20:
                            sb1.AppendFormat(" AND (RentPrice <={0})", hprice);
                            break;
                        case 30:
                            sb1.AppendFormat(" AND ((SalePrice_T <={0}) OR (RentPrice<={0}))", hprice);
                            break;
                    }
                }
                else
                {
                    sb1.AppendFormat(" AND ((SalePrice_T <={0}) and (RentPrice<={0}))", hprice);
                }
            }
            #endregion

            //描述：快速搜索参数拼接
            //添加人：熊世宏
            //添加日期：2010-04-20
            if (context.Request["quicktype"] != null)
            {
                switch (context.Request["quicktype"])
                {
                    case "owner"://我的房源
                        sb1.AppendFormat(" And(AddPersonId='{0}')", CurrentUserInfo.UserId);
                        break;
                    case "depart"://本店房源
                        sb1.AppendFormat(" And(AddDepartId='{0}')", CurrentUserInfo.DepartId);
                        break;
                    case "today"://本日房源
                        sb1.AppendFormat(" And (datediff(d,Adddate,'{0}')=0)", DateTime.Now);
                        break;
                    case "thismonth"://本月房源
                        sb1.AppendFormat(" And (datediff(m,Adddate,'{0}')=0)", DateTime.Now);
                        break;
                    case "key"://要是房源
                        sb1.Append(" And (IsHavekey='1')");
                        break;
                    case "favor":// 我的收藏
                        sb1.AppendFormat(" And (HouseId in (select FavorId from Personal_FavorsInfo where FavorPersonId = '{0}' and FavorType = 0 ))", CurrentUserInfo.UserId);
                        break;
                }
            }
            if (!string.IsNullOrEmpty(strKeyword)) sb1.AppendFormat(" AND ((Address Like '%{0}%') Or (HouseCode Like '%{0}%')  Or (BuildingName Like '%{0}%') Or (Room Like '%{0}%'))", strKeyword);
            if (!string.IsNullOrEmpty(strUserCode))
            {
                Chenxin.Lib.Passport.Entity.Hr_UserInfo hr = Chenxin.Lib.Passport.DAL.Hr_UserInfo.GetEntityByCode(strUserCode);
                if (hr != null) sb1.AppendFormat(" AND OprPersonId='{0}'", hr.UserId);
                hr = null;
            }

            if (!string.IsNullOrEmpty(strDayType))
            {
                if (!string.IsNullOrEmpty(strDayBegin))
                {
                    sb1.AppendFormat(" AND ({0} >= '{1}')", (strDayType == "0") ? "ServiceTime" : "Adddate", strDayBegin);
                }

                if (!string.IsNullOrEmpty(strDayEnd))
                {
                    sb1.AppendFormat(" AND ({0} < '{1}')", (strDayType == "0") ? "ServiceTime" : "Adddate", DateTime.Parse(strDayEnd).AddDays(1));
                }
            }  else
            {
                if (!string.IsNullOrEmpty(strDayBegin))
                {
                    sb1.AppendFormat(" AND ({0} >= '{1}')", "Adddate", strDayBegin);
                }

                if (!string.IsNullOrEmpty(strDayEnd))
                {
                    sb1.AppendFormat(" AND ({0} < '{1}')", "Adddate", DateTime.Parse(strDayEnd).AddDays(1));
                }
            }

            if (userId != Guid.Empty)
                sb1.AppendFormat(" AND (OprPersonId = '{0}') ", userId);
            else if (departId != Guid.Empty)
                sb1.AppendFormat(" AND (OprDepartId = '{0}')", departId);
            else if (areaId != Guid.Empty)
            {
                Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo item = null;
                string strCachkey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_DEPARTMENT, areaId);
                Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
                item = cs.GetObject<Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo>(strCachkey);
                if (!cs.Hit)
                {
                    item = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetModel(areaId);
                    if (item != null) cs.Set(strCachkey, item, DateTime.Now.AddDays(1));
                }

                if (item == null) context.Response.Write(string.Format("{{success:'0',msg:'{0}',data:''}}", "获取商圈或分类数据丢失"));

                sb1.AppendFormat(" AND (OprDepartId in (select departId from v_Hr_DepartmentInfo where DepartSrc like '{0}%'))", item.DepartSrc);
            }
            else if (companyId != Guid.Empty)
                sb1.AppendFormat(" AND (CompanyId = '{0}')", companyId);
            else if (cityId != Guid.Empty)
                sb1.AppendFormat(" AND (CityId = '{0}')", cityId);
            else
                sb1.AppendFormat(" AND (CompanyId = '{0}')", CurrentUserInfo.CompanyId);

            System.Text.StringBuilder sbOrder = new System.Text.StringBuilder();
            if (!string.IsNullOrEmpty(strOrderField))
            {
                sbOrder.AppendFormat(" Order By {0}", strOrderField);
            }
            else
            {
                sbOrder.Append(" UpdateTime DESC");
            }

    //判断权限范围/////////////////////////////////////////////
            System.Text.StringBuilder sb2 = new System.Text.StringBuilder();

            //查看所有库存权限
            if (CurrentUserInfo.ContainsPermit(Constants.Permit_Stock_All))
            {
                sb2.Append(" (1=1) ");
            }
            //查看城市库存权限
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_Stock_City))
            {
                sb2.AppendFormat(" CityId= '{0}' ", CurrentUserInfo.CityId);
            }
            //查看公司库存权限
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_Stock_Company))
            {
                sb2.AppendFormat(" CompanyId= '{0}' ", CurrentUserInfo.CompanyId);
            }
            //查看部门库存权限
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_Stock_Department))
            {
                sb2.Append("EXISTS(");
                sb2.Append("Select 1 from v_Struct_UserDepartRelation M ");
                sb2.AppendFormat("WHERE (House_BaseInfo.OprDepartId = M.Departid AND  M.Userid= '{0}' and ViewStock=1) ", CurrentUserInfo.UserId);
                sb2.Append(")");
            }
            else
            {
                sb2.AppendFormat(" (1=0) ", CurrentUserInfo.UserId);
            }
            
            if (sb1.ToString().Trim() != "")sb2.Append(sb1);
            
            System.Data.DataSet dshouselist = Chenxin.Lib.House.DAL.House_BaseInfo.GetList(
                iPageIndex, iPageSize, sbOrder.ToString(), "House_BaseInfo", sb2.ToString(), fieldlist, tablefieldlist, true);

            int count = (int)dshouselist.Tables[1].Rows[0][0];

            string strHtml ="";
            string canexport = context.Request["canexport"];
            if("10".Equals(canexport)) {
              if (!SubGetHouseListHtml(dshouselist, out strHtml))
              {
                  responseJson = string.Format("{{success:'0',msg:'{0}',data:''}}", "生成HTML错误");
              }
            } else {
              if (!GetHouseListHtml(dshouselist, out strHtml))
              {
                  responseJson = string.Format("{{success:'0',msg:'{0}',data:''}}", "生成HTML错误");
              }
            }
            dshouselist.Dispose();
            dshouselist = null;
            responseJson = string.Format("{{success:'1',msg:'{0}',data:{{count:'{1}',data:'{2}'}}}}", "成功", count, strHtml);
            context.Response.Write(responseJson);
        
        }
        catch (Exception ex)
        {
            responseJson = string.Format("{{success:'0',msg:'{0}',data:''}}", "生成HTML错误:" + ex.Message);
            context.Response.Write(responseJson);
        }
    }

    /// <summary>
    /// 根据参数中的房源ID查询房源跟单数据;
    /// 返回Json数据：{count:'30',data:'abc'}
    /// </summary>
    /// <param name="context"></param>
    private void GetHouseTraceList(HttpContext context)
    {
        Guid houseId = (string.IsNullOrEmpty(context.Request["houseid"])) ? Guid.Empty : new Guid(context.Request["houseid"]);
        string responseJson = "";
        try
        {
            if (houseId == Guid.Empty)
            {
                responseJson = string.Format("{{success:'0',msg:'{0}',data:''}}", "参数错误，房源标识丢失");
                context.Response.Write(responseJson);
                return;
            }

            int iPageIndex = (string.IsNullOrEmpty(context.Request["pageindex"])) ? 1 : int.Parse(context.Request["pageindex"]) + 1;//页码
            int iPageSize = (string.IsNullOrEmpty(context.Request["pagesize"])) ? 30 : int.Parse(context.Request["pagesize"]);//页记录数
            string fieldlist = "*";
            string fieldtablelist = "*";
            string orderfield = "House_TraceInfo.TraceTime desc";
            string strwhere = string.Format("(houseId='{0}' AND IsHide = 0 AND Status = 0)", houseId);

            System.Data.DataSet dshousetracelist = null;
            if (iPageIndex == 1)
            {
                //分页第一页从缓存中读取
                Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.HOUSE);
                string strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.HOUSE_TRACE, houseId);

                dshousetracelist = cs.GetDataSet(strCachKey);
                if (!cs.Hit)
                {
                    //若未命中。从查询数据库中读取
                    dshousetracelist = Chenxin.Lib.House.DAL.House_TraceInfo.GetList(
                        iPageIndex, iPageSize, orderfield, "House_TraceInfo", strwhere, fieldlist, fieldtablelist, true);

                    cs.Set(strCachKey, dshousetracelist, DateTime.Now.AddMinutes(5));
                }
            }
            else
            {
                dshousetracelist = Chenxin.Lib.House.DAL.House_TraceInfo.GetList(
                iPageIndex, iPageSize, orderfield, "House_TraceInfo", strwhere, fieldlist, fieldtablelist, true);
            }

            int count = (int)dshousetracelist.Tables[1].Rows[0][0];

            string strHtml = "";
            if (!GetHouseTraceListHtml(dshousetracelist, out strHtml))
            {
                responseJson = string.Format("{{success:'0',msg:'{0}',data:''}}", "生成HTML错误");
            }

            dshousetracelist.Dispose();
            dshousetracelist = null;
            responseJson = string.Format("{{success:'1',msg:'{0}',data:{{count:'{1}',data:'{2}'}}}}", "成功", count, strHtml);
            context.Response.Write(responseJson);
        }
        catch (Exception ex)
        {
            responseJson = string.Format("{{success:'0',msg:'{0}',data:''}}", "未知错误：" + ex.Message);
            context.Response.Write(responseJson);
            return;
        }
    }


    /// <summary>
    /// 获取展开层中需要房源数据。数据以实体转换成Json返回。
    /// </summary>
    /// <param name="context"></param>
    private void GetHouseInfo(HttpContext context)
    {
        Guid houseId = (string.IsNullOrEmpty(context.Request["houseid"])) ? Guid.Empty : new Guid(context.Request["houseid"]);
        string responseJson = "";
        try
        {
            if (houseId == Guid.Empty)
            {
                responseJson = string.Format("{{success:'0',msg:'{0}',data:''}}", "参数错误，房源标识丢失");
                context.Response.Write(responseJson);
                return;
            }

            Chenxin.Lib.House.Entity.House_BaseInfo item = null;
            //从缓存服务器读取房源信息
            Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
            //string strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_HOUSEINFO, houseId);
            //item = cs.GetObject(strCachKey) as Chenxin.Lib.House.Entity.House_BaseInfo;
            //if (!cs.Hit)//若未命中
            //{
                item = Chenxin.Lib.House.BLL.House_BaseInfo.GetHouseInfoEntity(houseId.ToString());
            //    cs.Set(strCachKey, item, DateTime.Now.AddHours(1));
            //}

            if (item == null)
            {
                responseJson = string.Format("{{success:'0',msg:'{0}',data:''}}", "参数错误，找不到对应的房源");
                context.Response.Write(responseJson);
                return;
            }

            responseJson = string.Format("{{success:'1',msg:'成功',data:{{houseinfo:{0}}}}}",
                Chenxin.Lib.Utility.JsonHelp.Convert2Json(item));

            context.Response.Write(responseJson);
        }
        catch (Exception ex)
        {
            responseJson = string.Format("{{success:'0',msg:'{0}',data:''}}", "未知错误：" + ex.Message);
            context.Response.Write(responseJson);
            return;
        }

    }

    private bool GetHouseListHtml(System.Data.DataSet dslist, out string strHtml)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        sb.Append("<table width=\"100%\" height=\"100%\" cellspacing=\"1\" class=\"tabsorternew\" id=\"report\">");
        sb.Append("<thead>");
        sb.Append("<tr>");
        sb.Append("<th width=\"30\">区域</th>");
        sb.Append("<th>楼盘/门号/房号</th>");
        sb.Append("<th width=\"30\" >交易</th>");
        sb.Append("<th width=\"38\">面积</th>");
        sb.Append("<th width=\"70\">价格</th>");
        sb.Append("<th width=\"60\" >部门</th>");
        sb.Append("<th width=\"60\">业务员</th>");
        sb.Append("<th width=\"108px\">跟盘时间</th>");
        sb.Append("<th width=\"70\">客户</th>");
        sb.Append("<th width=\"95\">客户电话</th>");
        sb.Append("<th width=\"30\">状态</th>");
        sb.Append("</tr></thead>");
        sb.Append("<tbody>");

        foreach (System.Data.DataRow row in dslist.Tables[0].Rows)
        {
            sb.AppendFormat("<tr id=\"{0}\" class=\"tr_houselist\">", row["HouseId"].ToString());
            //区域列
            sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Region", ""));
            //楼盘/门号/房号
            sb.AppendFormat("<td><a href=\"ShowDetailInfo.aspx?houseid={0}\" target=\"blank\">{1} {2} {3}</a></td>",
                    DatasetHelper.GetValue(row, "HouseId", Guid.Empty), DatasetHelper.GetValue(row, "Community", ""),
                DatasetHelper.GetValue(row, "BuildingName", ""),
                DatasetHelper.GetValue(row, "Room", ""));
            //交易列
            sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "BusinessKind", ""));
            string kind = Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Kind", "");
            //面积
            sb.AppendFormat("<td>{0:f2}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "BuildingArea", ""));
            //总价
            float price_t = Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "SalePrice_T", 0f);
            float price_u = Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "RentPrice", 0f);
            //出售
            if ("10".Equals(kind))
            {
                sb.AppendFormat("<td style=\"text-align:right;\">{0:f2}万元</td>", Math.Round(price_t)); 
            }
            //出租
            else if ("20".Equals(kind))
            {
                sb.AppendFormat("<td style=\"text-align:right;\" >{0:f2}元</td>", Math.Round(price_u));
            }
            // 租售
            else
            {
                sb.AppendFormat("<td style=\"text-align:right;\" >{0:f2}万元</td>", Math.Round(price_t));
            }
            //部门
            sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "OprDepart", ""));
            //业务员
            sb.AppendFormat("<td>{0:f0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "OprPerson", ""));
            //跟盘时间
            sb.AppendFormat("<td>{0:yyyy-MM-dd}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "ServiceTime", ""));

            sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "CustomerName", ""));
            
            sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "CustTel1", ""));

            sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Status", ""));

            sb.Append("</tr>");
        }

        sb.Append("</tbody></table> <input type=\"hidden\" value=\"no\" id=\"isExport\" />");

        strHtml = sb.ToString();
        return true;
    }

    private bool SubGetHouseListHtml(System.Data.DataSet dslist, out string strHtml)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        sb.Append("<table width=\"100%\" height=\"100%\" cellspacing=\"1\" class=\"tabsorternew\" id=\"report\">");
        sb.Append("<thead>");
        sb.Append("<tr>");
        sb.Append("<th width=\"30\">区域</th>");
        sb.Append("<th>楼盘/门号/房号</th>");
        sb.Append("<th width=\"30\" >交易</th>");
        sb.Append("<th width=\"40\">面积</th>");
        sb.Append("<th width=\"70\">价格</th>");
        sb.Append("<th width=\"60\" >部门</th>");
        sb.Append("<th width=\"60\">业务员</th>");
        sb.Append("<th width=\"105px\">跟盘时间</th>");
        sb.Append("<th width=\"70\">客户</th>");
        sb.Append("<th width=\"30\">状态</th>");
        sb.Append("</tr></thead>");
        sb.Append("<tbody>");

        foreach (System.Data.DataRow row in dslist.Tables[0].Rows)
        {
            sb.AppendFormat("<tr id=\"{0}\" class=\"tr_houselist\">", row["HouseId"].ToString());
            //区域列
            sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Region", ""));
            //楼盘/门号/房号
            sb.AppendFormat("<td><a href=\"ShowDetailInfo.aspx?houseid={0}\" target=\"blank\">{1} {2} {3}</a></td>",
                    DatasetHelper.GetValue(row, "HouseId", Guid.Empty), DatasetHelper.GetValue(row, "Community", ""),
                DatasetHelper.GetValue(row, "BuildingName", ""),
                DatasetHelper.GetValue(row, "Room", ""));
            //交易列
            sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "BusinessKind", ""));
            string kind = Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Kind", "");
            //面积
            sb.AppendFormat("<td>{0:f2}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "BuildingArea", ""));
            //总价
            float price_t = Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "SalePrice_T", 0f);
            float price_u = Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "RentPrice", 0f);
            //出售
            if ("10".Equals(kind))
            {
                sb.AppendFormat("<td style=\"text-align:right;\">{0:f2}万元</td>", Math.Round(price_t));
            }
            //出租
            else if ("20".Equals(kind))
            {
                sb.AppendFormat("<td style=\"text-align:right;\">{0:f2}元</td>", Math.Round(price_u));
            }
            // 租售
            else
            {
                sb.AppendFormat("<td style=\"text-align:right;\">{0:f2}万元</td>", Math.Round(price_t));
            }
            //部门
            sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "OprDepart", ""));
            //业务员
            sb.AppendFormat("<td>{0:f0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "OprPerson", ""));
            //跟盘时间
            sb.AppendFormat("<td>{0:yyyy-MM-dd}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "ServiceTime", ""));

            sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "CustomerName", ""));


            sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Status", ""));

            sb.Append("</tr>");
        }

        sb.Append("</tbody></table><input type=\"hidden\" value=\"can\" id=\"isExport\" />");

        strHtml = sb.ToString();
        return true;
    }
    /// <summary>
    /// 生成房源跟单列表
    /// </summary>
    /// <param name="dslist"></param>
    /// <param name="strHtml"></param>
    /// <returns></returns>
    private bool GetHouseTraceListHtml(System.Data.DataSet dslist, out string strHtml)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        //sb.Append("<div class=\"infos intitss\"><span class=\"rb\"><b>跟单内容</b></span><span class=\"rbpsn\"><b>跟单人</b></span>");
        //sb.Append("<span class=\"rbtim\"><b>跟单时间</b></span></div>");

        foreach (System.Data.DataRow row in dslist.Tables[0].Rows)
        {
            sb.AppendFormat("<div class=\"infos\" title=\"{0}\"> <span class=\"rb\">{0}</span><span class=\"rbpsn\">{1}</span><span class=\"rbtim\">{2:yyyy-MM-dd HH:mm}</span> </div>",
                DatasetHelper.GetValue(row, "TraceContext", ""),
                DatasetHelper.GetValue(row, "Tractor", "-") + "/" + DatasetHelper.GetValue(row, "Depart", "-"),
                DatasetHelper.GetValue(row, "TraceTime", ""));
        }

        strHtml = sb.ToString();
        return true;
    }


    /// <summary>
    /// 编辑
    /// </summary>
    /// <param name="context"></param>
    private void Edit(HttpContext context)
    {
        try
        {
            if (context.Request["model"] != null)
            {
                Chenxin.Lib.House.Entity.House_BaseInfo model = (Chenxin.Lib.House.Entity.House_BaseInfo)JsonHelp.Convert2Entity(context.Request["model"], typeof(Chenxin.Lib.House.Entity.House_BaseInfo));

                model.UpdateTime = DateTime.Now;
                model.ServiceTime = DateTime.Now;

                Chenxin.Lib.House.DAL.House_BaseInfo.ExecuteSQL("update dbo.House_BaseInfo set Status=" + model.Status + ",Remarks='" + model.Remarks + "',UpdateTime='" + model.UpdateTime.Value.ToString() + "',ServiceTime='" + model.ServiceTime.Value.ToString() + "' where HouseId='"+model.HouseId+"' ");

                context.Response.Write(string.Format("{{success:'1',msg:'保存成功！',data:{{HouseId:'{0}'}}}}", model.HouseId));
                
            }
            else 
            {
                context.Response.Write("{success:'1',msg:'保存失败！',data:''}");
            }
        }
        catch
        {
            context.Response.Write("{success:'1',msg:'保存失败！',data:''}");
        }
    }
}